<?php
namespace teia\webdev\php\admin;

$inc_core = realpath(dirname(__FILE__) . '/../../sbangola/teia.lib/inc/inc_core.inc');
require_once $inc_core;
use teia\webdev\php\core as teia_core;

class DataRegistratioinUtil {
	static  function db_insert_csv($db_tb, $target_cols, $file_path, $del=';', $verbose=TRUE) {
		$data = self::csv_load_file($target_cols, $file_path, $del);
		$count = 0;
		if ($data) {
			$num_rows = count($data);
			$file_info = "CSV file '$file_path' [$num_rows]";
			if ($verbose) echo "Loaded data from $file_info\n";
			$count = self::db_insert_data($db_tb, $data, $verbose);
		}
		return ($count > 0);
	}

	static function db_insert_data($db_tb, $data, $verbose=TRUE) {
		$total = 0;
		try {
			$db_link = teia_core\MySqlLink::link_factory();
			foreach ($data as $row_data) {
				try {
					$count = $db_link->insert($db_tb, $row_data);
					if ($count > 0) {
						$total += $count;
						if ($verbose) echo "\t- Added [$count]: \n" .teia_core\FunctionPool::assoc_to_str($row_data, "\n") . "\n\n";
					} else {
						if ($verbose) echo "\t- Failed to add [$count]: \n" .teia_core\FunctionPool::assoc_to_str($row_data, "\n") . "\n\n";
					}
				} catch (\Exception $e) {
					if ($verbose) {
						echo "\t- Failed to add: \n" .teia_core\FunctionPool::assoc_to_str($row_data, "\n") . "\n";
						echo "\t- Reason: " . $e->getMessage() . '[' . $e->getCode() . "]\n\n";
					}
				}
			}
		} catch (\Exception $e) {
			if ($verbose) echo "Failed to create MySql-Link: "  . $e->getMessage() . '[' . $e->getCode() . "]\n";
		}

		return $total;
	}

	static function csv_load_file($target_cols, $file_path, $del=';', $verbose=TRUE) {
		$csv = teia_core\FunctionPool::parse_csv_file($file_path, 'r', 0, $del);
		$num_rows = count($csv) - 1;
		$file_info = "CSV file '$file_path' [$num_rows]";
		$data = null;
		if ($num_rows > 0) {
			$cols = $csv[0];
			$indexes = teia_core\FunctionPool::array_search($target_cols, $cols);
			if ($indexes) {
				// read data starting from row 1
				$data = array();
				for ($r = 1; $r <= $num_rows; $r++) {
					$row = $csv[$r];
					// $num_cols = count($row);
					// echo "\t- Reading row '$r' with size $num_cols\n";
					$row_data = array();
					foreach ($indexes as $i) {
						$key = $cols[$i];
						$row_data[$key] = $row[$i];
					}
					array_push($data, $row_data);
				}
			} else {
				if ($verbose) echo "Not all expected columns were found in $file_info\n";
			}
		} else {
			if ($verbose) echo "No data found in $file_info\n";
		}

		return $data;
	}
}
?>